package com.example.mybluetooth;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.zip.Inflater;

public class MainActivity extends AppCompatActivity {
    private Button open, seach;
    private ListView ls;
    private Adapter adapter;
    private BluetoothDevice device;
    private BluetoothDevice devices;//已经配对的设备
    private List<pojo> list = new ArrayList<>();
    private List<BluetoothDevice> deviceList = new ArrayList<>();
    private BluetoothAdapter mBluetoothAdapter;//蓝牙适配器


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        initveiw();
    }

    private void initveiw() {
        open = findViewById(R.id.open);
        seach = findViewById(R.id.seach);
        ls = findViewById(R.id.ls);
        open.setOnClickListener(view -> OpenBluetooth());
        seach.setOnClickListener(view -> SeachBluetooth());
        IntentFilter discoveryFilter = new IntentFilter();
        discoveryFilter.addAction(BluetoothDevice.ACTION_FOUND);
        //注册蓝牙设备搜索的广播接收器
        registerReceiver(discoveryReceiver, discoveryFilter);
        ls.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    device = deviceList.get(i);
                    if (device.getBondState()==BluetoothDevice.BOND_NONE){
                        Log.i("TAGFF", "onItemClick: ");
                        Intent intent =  new Intent(MainActivity.this,BlueSocketTest.class);
                        intent.putExtra("name",device.getName());
                        intent.putExtra("address",device.getAddress());
                        Log.i("test", "onItemClick: ");
                        startActivity(intent);
                    }
                 pinBlue(device);
            }
        });
    }

    private void SeachBluetooth() {
        Log.i("TAGGGGGG", "SeachBluetooth: ");
        if (mBluetoothAdapter.isDiscovering()) {
            Log.i("TAG", "SeachBluetooth: ------》if");
            mBluetoothAdapter.cancelDiscovery();
        }
        //    搜素蓝牙设备
        Log.i("TAG", "SeachBluetooth:======》seach ");
        mBluetoothAdapter.startDiscovery();
    }

    private void OpenBluetooth() {
        Log.i("TAG", "OpenBluetooth: ");
        if (mBluetoothAdapter != null) {
            if (!mBluetoothAdapter.isEnabled()) {
                mBluetoothAdapter.enable();
            }
        } else {
            Toast.makeText(this, "该设备不支持蓝牙功能", Toast.LENGTH_SHORT).show();
        }
    }

    private BroadcastReceiver discoveryReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.i("connet", action);
            //获得已经搜索到的蓝牙设备
            if (action.equals(BluetoothDevice.ACTION_FOUND)) {//发现新的蓝牙设备
                device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//                Log.i("TAG", "onReceive: "+device);
                Log.i("TAG", "onReceive: " + device.getName());
                Log.i("TAG", "onReceive: " + device.getAddress());
                list.add(new pojo(device.getName(), device.getAddress()));
                deviceList.add(device);
                adapter = new Adapter(MainActivity.this, R.layout.item, list);
                ls.setAdapter(adapter);
                adapter.notify();
            }
        }
    };


    /**
     * 连接蓝牙设备
     */
    public void pinBlue(BluetoothDevice device) {
        if (device == null) {
            Log.e("TAG", "bond device null");
            return;
        }
        //配对之前把扫描关闭
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
        //判断设备是否配对，没有配对在配，配对了就不需要配了
        if (device.getBondState() == BluetoothDevice.BOND_NONE) {
            Log.d("TAGFF", "attemp to bond:" + device.getName());
            try {
                Method createBondMethod = device.getClass().getMethod("createBond");
                createBondMethod.invoke(device);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.e("TAGFF", "attemp to bond fail!");
            }
        }else {
            Intent intent =  new Intent(MainActivity.this,BlueSocketTest.class);
            intent.putExtra("name",device.getName());
            intent.putExtra("address",device.getAddress());
            Log.i("test", "onItemClick: ");
            startActivity(intent);
        }
    }

}